import { defineStore } from "pinia"
import { computed, ref, reactive } from "vue"
import { INVALID_ASSISTANT_ID } from "../constants"
import { result } from "@/utils/result"
import { get_assistant, create_assistant, update_assistant } from "@/api/assistant"
import { CODE } from "@/api/constants"
import useAssistantListStore from "@/stores/assistantList"

const default_system_msg = "你是一个论文阅读助手，能根据获取到的论文文档内容，用通俗易懂的方式解答我的疑问。"

const useAssistantSettingStore = defineStore('assistant-setting', () => {

    // 助理参数
    const assistantForm = reactive({})
    const initAssistantForm = () => {
        return {
            name: "",
            paper_id: "",
            system_msg: default_system_msg,
        }
    }
    Object.assign(assistantForm, initAssistantForm())
    const isAssistantFormReady = computed(() => {
        return !!assistantForm.name.trim()
    })
    const copyAssistantForm = (newForm) => {
        Object.assign(assistantForm, initAssistantForm())
        assistantForm.name = newForm.name
        assistantForm.paper_id = newForm.paper_id
        assistantForm.system_msg = newForm.system_msg
    }

    // 模型参数
    const modelForm = reactive({})
    const initModelForm = () => {
        return {
            llm_factory: "",
            api_key: "",
            llm: {},
            llm_setting: {
                temperature: 0.5,
                top_p: 0.5,
                frequency_penalty: 0.7,
                presence_penalty: 0.4,
            },
            fieldSwitches: {
                temperature: true,
                top_p: true,
                frequency_penalty: true,
                presence_penalty: true
            }
        }
    }
    Object.assign(modelForm, initModelForm())
    const isModelFormReady = computed(() => {
        return modelForm.llm_factory !== "" &&
            modelForm.api_key !== "" &&
            Object.keys(modelForm.llm).length !== 0
    })
    const copyModelForm = (newForm) => {
        Object.assign(modelForm, initModelForm())
        modelForm.llm_factory = newForm.llm_factory
        modelForm.api_key = newForm.api_key
        modelForm.llm = reactive(newForm.llm)
        for (const key in modelForm.fieldSwitches) {
            if (newForm.llm_setting.hasOwnProperty(key)) {
                modelForm.llm_setting[key] = newForm.llm_setting[key]
                if (modelForm.llm_setting[key] < 1e-6) {
                    modelForm.fieldSwitches[key] = false
                }
            } else {
                modelForm.fieldSwitches[key] = false
            }
        }
    }
    const makeModelFormReq = () => {
        const body = {}
        body.llm_factory = modelForm.llm_factory
        body.api_key = modelForm.api_key
        body.llm = modelForm.llm
        body.llm_setting = {}
        Object.entries(modelForm.fieldSwitches).forEach(([key, value]) => {
            if (value) {
                body.llm_setting[key] = modelForm.llm_setting[key]
            }
        })
        return body
    }
    
    const assistantId = ref(INVALID_ASSISTANT_ID)
    const setAssistantId = async (id) => {
        assistantId.value = id
        if (assistantId.value === INVALID_ASSISTANT_ID) {
            // reset
            Object.assign(assistantForm, initAssistantForm())
            Object.assign(modelForm, initModelForm())
            return result(true, "清空AssistantSetting信息成功")
        }
        // todo: 根据id向后端api获取初始数据，并设置，失败返回error
        const resp = await get_assistant({assistantId: assistantId.value})
        if (resp.code != CODE.OK) {
            return result(false, `获取助理信息失败：${resp.msg}`)
        }
        copyAssistantForm(resp.data.assistant_setting)
        copyModelForm(resp.data.model_setting)
        return result(true, `获取助理信息ID：${assistantId.value}成功`)
    }

    const isOkBtnDisabled = computed(() => {
        return !isModelFormReady.value || !isAssistantFormReady.value
    })

    const createAssistant = async () => {
        const resp = await create_assistant({
            assistant_setting: assistantForm, model_setting: makeModelFormReq()})
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        useAssistantListStore().pushMeta(resp.data)
        return result(true, "创建新助理成功")
    }

    const updateAssistant = async () => {
        const resp = await update_assistant({ assistantId: assistantId.value,
            assistant_setting: assistantForm, model_setting: makeModelFormReq()})
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        useAssistantListStore().repushMeta(resp.data)
        return result(true, "助理设置成功")
    }

    return { createAssistant, updateAssistant, setAssistantId, isOkBtnDisabled, assistantForm, modelForm }
})

export default useAssistantSettingStore;